
import {
  RECEIVE_ADDRESS,
  RECEIVE_CATEGORIES,
  RECEIVE_SHOPLIST,
} from '../mutation-types'

import {
  reqAddress,
  reqGoodCategories,
  reqShopList,
} from 'api'

const state = {
  latitude: '40.10038',
  longitude: '116.36867',
  address: {},
  categories: [],
  shoplists: [],
}

const actions = {
  async getAddress({commit,state}){
    //send ajax
    const {longitude,latitude} = state
    const newAddress = await reqAddress(longitude,latitude)
    if(newAddress.code === 0){
      const address = newAddress.data
      commit(RECEIVE_ADDRESS,address)
    }
  },
  async getCategories({commit},callback){
    const categories = await reqGoodCategories()
    if(categories.code === 0){
      const newCategories = categories.data
      commit(RECEIVE_CATEGORIES,newCategories)
      typeof callback === 'function' && callback()
    }
  },
  async getShoplists({commit,state}){
    const {longitude,latitude} = state
    const shoplist = await reqShopList({longitude,latitude})
    if(shoplist.code === 0){
      const newShoplist = shoplist.data
      commit(RECEIVE_SHOPLIST,newShoplist)
    }
  },
}

const mutations = {
  [RECEIVE_ADDRESS](state,address){
    state.address = address
  },
  [RECEIVE_CATEGORIES](state,newCategories){
    state.categories = newCategories
  },
  [RECEIVE_SHOPLIST](state,newShoplists){
    state.shoplists = newShoplists
  }
}

const getters = {
}

export default {
  state,
  mutations,
  actions,
  getters,
}
